import React, {Component} from 'react';
import {connect} from 'react-redux';
import {getPosts,getCategories} from "../actions";
import Posts from '../components/Posts';
import { browserHistory } from 'react-router'
class PostsContainer extends Component {
  constructor(props) {
    super(props);
    this.handlePageClick = this.handlePageClick.bind(this)
    this.getCategoryParams = this.getCategoryParams.bind(this)
    this.getPageParams = this.getPageParams.bind(this)
  }

  componentWillMount() {
    this.props.getPosts()
  }
  createMarkup(html) {
    return {__html: html};
  }
  getPageParams() {
    let page = parseInt(this.props.params.pageNum)
    return isNaN(page) ? 1 : page;
  }
  getCategoryParams() {
    let category = this.props.params.categorySlug;
    return typeof category === 'undifined' ? '' : category;
  }
  handlePageClick(selected){
   let pageNow = selected.selected + 1;
   // let pageParam = this.getPageParams();
   let cateParam = this.getCategoryParams();
   if (cateParam) {
     browserHistory.push(`/category/${cateParam}/${pageNow}`)
   } else {
     browserHistory.push(`/page/${pageNow}`)
   }


  }
  componentWillMount() {
    let pageParams = this.getPageParams()
    let categoryParams = this.getCategoryParams()
    this.props.getPosts(
      {
        page:pageParams,
        category:categoryParams,
      }
    )
    // 获取分类
    this.props.getCategories()
  }
  componentWillReceiveProps(nextProps) {
    let prevPageNum = this.getPageParams();
    let nextPageNum = nextProps.params.pageNum;
    nextPageNum = isNaN(nextPageNum) ? 1 : nextPageNum;

    let prevCategory = this.getCategoryParams();
    let nextCategory = nextProps.params.categorySlug;
    nextCategory = typeof nextCategory === 'undifined' ? '' : nextCategory;

    if (prevPageNum != nextPageNum
      || prevCategory != nextCategory) {
      this.props.getPosts(
        {
          page: nextPageNum,
          category:nextCategory
        }
      )
    }

  }
  render() {
    return (
      <Posts {...this.props} {...this} />
    );
  }
}


function mapStateToProps(store) {
  return {
    postList: store.posts.posts,
    totalPages: store.posts.totalPages,
    categories: store.categories.categories,
  }
}

export default connect(mapStateToProps, {getPosts,getCategories})(PostsContainer);